package com.ww.netty.basic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;

import java.util.concurrent.TimeUnit;

public class InHandlerDemoTester {

    // 打印结果
//    被调用handlerAdded()
//    被调用channelRegistered()
//    被调用channelActive()
//12:19:48.879 [main] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true
//            12:19:48.879 [main] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true
//            12:19:48.879 [main] DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@11c20519
//    被调用channelRead()
//    被调用channelReadComplete()
//    被调用channelRead()
//    被调用channelReadComplete()
//    被调用channelInactive()
//    被调用channelUnregistered()
//    被调用handlerRemoved()
    public static void main(String[] args) {
        final InHandlerDemo inHandlerDemo = new InHandlerDemo();
        // 初始化处理器
        ChannelInitializer<EmbeddedChannel> initializer = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel embeddedChannel) throws Exception {
                embeddedChannel.pipeline().addLast(inHandlerDemo);
            }
        };

        // 创建嵌入式通道
        EmbeddedChannel channel = new EmbeddedChannel(initializer);
        ByteBuf buf = Unpooled.buffer();
        buf.writeInt(1);
        // 模拟入站，写一个入站数据包
        channel.writeInbound(buf);
        channel.flush();
        // 默认入站，再写一个入站数据数据包
        channel.writeInbound(buf);
        channel.flush();
        // 通道关闭
        channel.close();

        try {
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
